import redisHelper from './redisHelper.js';
import logger from './logger.js';
import db from './mysqlHelper.js';

//根据车场编号获取项目信息
async function getProjectInfo(parkNo) {
    let key = `projectInfo:${parkNo}`;
    try {
        let projectInfo = await redisHelper.get(key);
        if (projectInfo == null) {
            let project = await db.findOne('project', { park_no: parkNo });
            if (project != null) {
                await redisHelper.setAutoExpire(key, JSON.stringify(project));
                return project;
            } else {
                return null;
            }
        } else {
            return JSON.parse(projectInfo);
        }
    } catch (error) {
        logger.error(`getProjectInfo error :` + error.message, `parkNo:${parkNo}`);
        return null;
    }
}
//根据ISPID获取ISP信息
async function getISPInfo(ISPID) {
    let key = `ISPInfo:${ISPID}`;
    try {
        let ISPInfo = await redisHelper.get(key);
        if (ISPInfo == null) {
            let ISP = await db.findOne('isp', { id: ISPID });
            if (ISP != null) {
                await redisHelper.setAutoExpire(key, JSON.stringify(ISP));
                return ISP;
            } else {
                return null;
            }
        } else {
            return JSON.parse(ISPInfo);
        }
    } catch (error) {
        logger.error(`getISPInfo error :` + error.message, `ISPID:${ISPID}`);
        return null;
    }
}

//获取全局并发锁
async function getGlobalLock(key, expire) {
    let lockKey = `lock:${key}`;
    let lockValue = Math.random().toString(36).substr(2);
    let result = await redisHelper.setnx(lockKey, lockValue, expire);
    return result;
}

async function releaseGlobalLock(key) {
    let lockKey = `lock:${key}`;
    await redisHelper.del(lockKey);
}

export default { getProjectInfo, getISPInfo, getGlobalLock, releaseGlobalLock };
